package com.chinasoft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinasoft.domain.Department;
import com.chinasoft.query.PageQuery;
import com.chinasoft.service.DepartmentService;
import com.chinasoft.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理接口
 *  要求前后端传递参数必须使用json对象
 *  写接口的三要素：
 *    1.请求地址是什么
 *    2.请求参数是什么
 *    3.返回值是什么
 */
@CrossOrigin
@RestController// = @Controller + @ResponseBody
@RequestMapping("/dept")// http://localhost:8080/dept
//@GetMapping =@RequestMapping(value = "/id",method = RequestMethod.GET)
//@PostMapping
//@PutMapping

public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    /**
     * 新增和修改
     * @param department
     * @return
     */
    @PutMapping
    public AjaxResult addOrUpDate(@RequestBody Department department){

        try {
            departmentService.saveOrUpdate(department);
            return AjaxResult.me();
        } catch (Exception e) {
           e.printStackTrace();
           return AjaxResult.me().setSuccess(false).setMessage("程序错误，请联系管理员");
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("程序错误，请联系管理员");
        }
    }

    /**
     * 查询单条记录
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.getById(id);
    }
    /**
     * 查询所有
     */
    @GetMapping// http://localhost:8081/dept
    public List<Department> queryAll(){
        return departmentService.list();
    }
    /**
     * 分页查询
     */
    @PostMapping
    public AjaxResult queryPage( @RequestBody PageQuery pageQuery){
        //System.out.println(pageQuery);
        Page<Department> departmentPage = new Page<>(pageQuery.getCurrentPage(),pageQuery.getPageSize());
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        /*
        判断前端传过来的keywords是否为空，如果为空则无条件查询所有；如果有值，执行有条件分页查询
         */
        if(pageQuery.getKeywords()!=null){
            departmentQueryWrapper.like("sn",pageQuery.getKeywords()).or().like("name",pageQuery.getKeywords());
        }
        Page<Department> page = departmentService.page(departmentPage,departmentQueryWrapper);
        return AjaxResult.me().setResultObj(page);
    }

}
